/**
 * 2021年8月29日 08:55:46 chanchaw
 * 白坯计划序时表
 */
$(function () {
    let buttonGroup = [
        {
            id: 'btn_add',
            size: 'small',
            text: '新增单据',
            iconCls: 'icon-add',
            onClick: btn_add,
            plain: true
        },
        {
            id: 'btn_KCMX',
            size: 'small',
            text: '车号明细',
            iconCls: 'icon-exclamation',
            onClick: btn_KCMX,
            plain: true
        },
        {
            id: 'btn_cancel_filter',
            size: 'small',
            text: '清除过滤',
            iconCls: 'icon-clear',
            plain: true,
            onClick: btn_cancel_filter
        },
        {
            id: 'btn_export',
            size: 'small',
            text: '导出Excel',
            iconCls: 'icon-page_excel',
            plain: true,
            onClick: btn_export_excel
        },
        {
            id: 'btn_finish',
            size: 'small',
            text: '订单完成',
            iconCls: 'icon-user_gray',
            onClick: btn_finish,
            plain: true
        },
        {
            id: 'btn_cancel_finish',
            size: 'small',
            text: '取消完成',
            iconCls: 'icon-user_delete',
            onClick: btn_cancel_finish,
            plain: true
        },
        /*{
            id: 'btn_delete',
            size: 'small',
            text: '作废',
            iconCls: 'icon-cancel',
            onClick: btn_delete,
            plain: true
        },*/
        {
            id: 'btn_cancel_search',
            size: 'small',
            text: '作废查询',
            iconCls: 'icon-search',
            onClick: btn_cancel_search,
            plain: true
        },
        // {
        //     id: 'btn_print',
        //     size: 'small',
        //     text: '打印',
        //     iconCls: 'icon-print',
        //     plain: true,
        //     // onClick: btn_print_new
        //     onClick:openPrint
        // },
        // {
        //     id: 'btn_zykc',
        //     size: 'small',
        //     text: '转移库存',
        //     iconCls: 'icon-redo',
        //     plain: true,
        //     onClick: getDataA
        //     // onClick:ceshi
        // },
        {
            id: 'btn_grid_columns',
            size: 'small',
            text: '列',
            iconCls: 'icon-text_columns',
            plain: true,
            onClick: btn_open_column_list
        },
        // {
        //     id: 'btn_audit',
        //     size: 'small',
        //     text: '一键审核',
        //     iconCls: 'icon-exclamation',
        //     onClick: btn_audit,
        //     plain: true
        // },
        // {
        //     id: 'btn_cancel_audit',
        //     size: 'small',
        //     disabled: true,
        //     text: '消审',
        //     iconCls: 'icon-exclamation',
        //     onClick: btn_cancel_audit,
        //     plain: true
        // },
        {
            id: 'btn_close', size: 'small', text: '关闭', iconCls: 'icon-no', onClick: btn_close,
            plain: true
        },
        // {
        //     id: 'btn_moveInven', size: 'small', text: '移库', iconCls: 'icon-no', onClick: btn_moveInven,
        //     plain: true
        // },
    ];

    buttonGen($('#north'), buttonGroup);
    grid_1();
    bindEnterEvents();

    let kGrid = $('#v_grid').data('kendoGrid');
    var options = kGrid.getOptions();
    if (options.columns.length > 0)
        initCombobox(options)
})

// 移库 弹出模态窗的字段配置
const materialColumns = [
    {title: 'id', field: 'id', hidden: true,},
    // {title: '件数', field: 'boxAmount', editor: {type: 'numberbox', options: {precision: 1, required: false}}},
    {title: '移库匹数', field: 'inputAmount', id: 'inputAmount',editor: {type: 'numberbox', options: {precision: 0, required: true}}},
    {
        title: '移库重量',
        id: 'inputKiloId',
        field: 'inputKilo',
        editor: {type: 'numberbox', options: {precision: 1, required: true}}
    },
];

const PrintColumns = [];

const planColumns = [
    {title: 'id', field: 'id', hidden: true,},
    {
        title: '计划对应的批次号',
        hidden: true,
        field: 'detail',
        id: 'detailInput',
    },
    {
        title: '订单号',
        field: 'code',
        id: 'code',
        editor: {type: 'textbox', options: {required: true, readonly: false, cls: 'input-blue'}}
    },
    {
        title: '客户',
        hidden: true,
        field: 'client',
        id: 'client',
    },
    {
        title: '客户单号',
        hidden: true,
        field: 'alias',
        id: 'alias',
    },
    // {
    //     title: '客&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;户', field: 'client', editor: {
    //         type: 'combobox', options: {
    //             url: 'contactCompany/listQuery',
    //             method: 'GET', queryParams: {state: 1},
    //             textField: 'companyName', valueField: 'id',
    //             cls: 'input-blue',
    //             panelHeight: 200,
    //             required: true,
    //             onLoadSuccess: function () {
    //                 $(this).combobox('options').limitToList = true;
    //             },
    //             onSelect: function(record) {
    //                 // $('#alias').textbox('setValue', record.companyName);
    //                 $.ajax({
    //                     url: 'producePlan/selectMax',
    //                     type: 'GET',
    //                     dataType: 'json',
    //                     contentType: 'application/json',
    //                     success: function (data) {
    //                         if (data) {
    //                             let date = new Date();
    //                             let year = date.getFullYear();
    //                             let orderCodeYear = (data.orderCodeYear + 1).toString().padStart(3, '0');
    //                             if (!$('#code').textbox('getValue')) $('#code').textbox('setValue', 'BYJ' + year + '-' + orderCodeYear);
    //                         } else {
    //                             $.messager.alert('提示', data.message, 'warning');
    //                         }
    //                     },
    //                     complete: function () {
    //                         $.messager.progress('close');
    //                     }
    //                 })
    //             }
    //         }
    //     }
    // },
    // {
    //     title: '客户单号',
    //     field: 'alias',
    //     id: 'alias',
    //     editor: {type: 'textbox', options: {required: false, cls: 'input-blue',}}
    // },
    {
        title: '下单日期',
        field: 'billDate',
        editor: {type: 'datebox', options: {value: getCurrentDate(), required: true, cls: 'input-blue',}}
    },
    {
        field: "shippingDate",
        title: '出货日期',
        editor: {type: 'datebox', options: {required: false, cls: 'input-blue',}}
    },
    {
        title: '品&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;名',
        field: 'productName',
        editor: {
            type: 'combobox',
            options: {
                required: true,
                url: 'productInfo/listQuery',
                method: 'GET',
                textField: 'productName',
                valueField: 'productName',
                cls: 'input-red',
                panelHeight: 200
            }
        }
    },
    {
        title: '坯布门幅',
        field: 'fabricWidth',
        editor: {type: 'textbox', options: {required: false, cls: 'input-blue',}}
    },
    {
        title: '克重',  /*原坯布规格*/
        field: 'fabricSpecification',
        editor: {type: 'textbox', options: {required: false, cls: 'input-blue',}}
    },
    {
        title: '定长定重',
        field: 'productSpecification',
        editor: {type: 'textbox', options: {required: false, cls: 'input-blue',}}
    },
    {
        title: '计划公斤',
        field: 'kilo',
        editor: {type: 'numberbox', options: {precision: 1, required: true, cls: 'input-blue',}}
    },
    {
        title: '上机数',
        field: 'machineQty',
        editor: {type: 'numberbox', options: {required: false, cls: 'input-blue',}}
    },
    {
        title: '总经',
        field: 'yarnTotal',
        editor: {type: 'textbox', options: {required: false, cls: 'input-blue',}}
    },
    {
        title: '经纱',
        field: 'longitude',
        editor: {type: 'textbox', options: {required: false, cls: 'input-blue',}}
    },
    {
        title: '经长',
        field: 'yarnLong',
        editor: {type: 'textbox', options: {required: false, cls: 'input-blue',}}
    },
    {
        title: '纬纱',
        field: 'latitude',
        editor: {type: 'textbox', options: {required: false, cls: 'input-blue',}}
    },
    {
        title: '经纬密度',
        field: 'latilong',
        editor: {type: 'textbox', options: {required: false, cls: 'input-blue',}}
    },
    {
        title: '颜色',
        field: 'color',
        editor: {type: 'textbox', options: {required: false, cls: 'input-blue',}}
    },
    {
        title: '筘幅',
        field: 'kouWidth',
        editor: {type: 'textbox', options: {required: false, cls: 'input-blue',}}
    },
    // {
    //     title: '打印本厂名称',
    //     field: 'isMarking',
    //     id: 'isMarking',
    //     editor: {type: 'checkbox', options: {value: 1, checked: true,}}
    // },
    {
        title: '备注',
        field: 'remark',
        editor: {type: 'textbox', options: {required: false, cls: 'input-blue', width: 500}}
    },
];

//  计划管理 - 白坯计划
function grid_1() {
    let SUFFIX = "";
    let client = new kendo.data.DataSource({data: []});
    let bill_date = new kendo.data.DataSource({data: []});
    let shipping_date = new kendo.data.DataSource({data: []});
    let shippingDate = new kendo.data.DataSource({data: []});
    let product_name = new kendo.data.DataSource({data: []});
    let product_specification = new kendo.data.DataSource({data: []});
    let fabric_specification = new kendo.data.DataSource({data: []});
    let color = new kendo.data.DataSource({data: []});
    let piece = new kendo.data.DataSource({data: []});
    let kilo = new kendo.data.DataSource({data: []});
    let machine_qty = new kendo.data.DataSource({data: []});
    let yarn_total = new kendo.data.DataSource({data: []});
    let longitude = new kendo.data.DataSource({data: []});
    let latitude = new kendo.data.DataSource({data: []});
    let yarn_long = new kendo.data.DataSource({data: []});
    let latilong = new kendo.data.DataSource({data: []});
    let fabric_width = new kendo.data.DataSource({data: []});
    let remarks = new kendo.data.DataSource({data: []});
    let create_user = new kendo.data.DataSource({data: []});
    let last_time = new kendo.data.DataSource({data: []});
    let last_user = new kendo.data.DataSource({data: []});
    let is_show_order = new kendo.data.DataSource({data: []});
    let order_code_year = new kendo.data.DataSource({data: []});
    let company_name = new kendo.data.DataSource({data: []});
    let billDate = new kendo.data.DataSource({data: []});
    let alias = new kendo.data.DataSource({data: []});
    let kou_width = new kendo.data.DataSource({data: []});
    let low_weights = new kendo.data.DataSource({data: []});
    let fhps = new kendo.data.DataSource({data: []});
    let fhqty = new kendo.data.DataSource({data: []});
    let kcps = new kendo.data.DataSource({data: []});
    let kcqty = new kendo.data.DataSource({data: []});

    // console.log('请求序时表数据的参数依次是：',$('#start').datebox('getValue'),$('#end').datebox('getValue'),
    //     $('#state').switchbutton('options').checked ? $('#state').switchbutton('options').checked : null)
    let dataSource = new kendo.data.DataSource({
        transport: {
            read: {
                url: "producePlan/report",
                dataType: "json",
                type: "GET",
                data: {
                    start: $('#start').datebox('getValue'),
                    end: $('#end').datebox('getValue'),
                    stateNumber: 1,
                }
            }
        },
        schema: {
            model: {
                id: 'id',
                fields: {
                    kilo: {type: "number"},
                    rkps: {type: "number"},
                    rkqty: {type: "number"},
                    yfhps: {type: "number"},
                    yfhqty: {type: "number"},
                    fhps: {type: "number"},
                    fhqty: {type: "number"},
                    kcps: {type: "number"},
                    kcqty: {type: "number"},
                }
            }
        },
        aggregate: [
            {field: "kilo", aggregate: "sum"},
            {field: "rkps", aggregate: "sum"},
            {field: "rkqty", aggregate: "sum"},
            {field: "yfhps", aggregate: "sum"},
            {field: "yfhqty", aggregate: "sum"},
            {field: "fhps", aggregate: "sum"},
            {field: "fhqty", aggregate: "sum"},
            {field: "kcps", aggregate: "sum"},
            {field: "kcqty", aggregate: "sum"},
        ],
        change: function (e) {
            let data = this.data();
            client.data(unique(data, 'client'));
            bill_date.data(unique(data, 'bill_date'));
            shipping_date.data(unique(data, 'shipping_date'));
            shippingDate.data(unique(data, 'shippingDate'));
            product_name.data(unique(data, 'product_name'));
            product_specification.data(unique(data, 'product_specification'));
            fabric_specification.data(unique(data, 'fabric_specification'));
            color.data(unique(data, 'color'));
            piece.data(unique(data, 'piece'));
            kilo.data(unique(data, 'kilo'));
            machine_qty.data(unique(data, 'machine_qty'));
            yarn_total.data(unique(data, 'yarn_total'));
            longitude.data(unique(data, 'longitude'));
            latitude.data(unique(data, 'latitude'));
            yarn_long.data(unique(data, 'yarn_long'));
            latilong.data(unique(data, 'latilong'));
            fabric_width.data(unique(data, 'fabric_width'));
            remarks.data(unique(data, 'remark'));
            create_user.data(unique(data, 'create_user'));
            last_time.data(unique(data, 'last_time'));
            last_user.data(unique(data, 'last_user'));
            is_show_order.data(unique(data, 'is_show_order'));
            order_code_year.data(unique(data, 'order_code_year'));
            company_name.data(unique(data, 'company_name'));
            billDate.data(unique(data, 'billDate'));
            alias.data(unique(data, 'alias'));
            kou_width.data(unique(data, 'kou_width'));
            low_weights.data(unique(data, 'low_weights'));
            fhps.data(unique(data, 'fhps'));
            fhqty.data(unique(data, 'fhqty'));
            kcps.data(unique(data, 'kcps'));
            kcqty.data(unique(data, 'kcqty'));

            $('#btn_cancel_audit').linkbutton('disable')
            //获取过滤条件
            var filtrer = this.filter();
            //获取所有数据
            var allData = this.data();
            //进行过滤条件的筛选
            var query = new kendo.data.Query(allData);
            //获取过过滤后的数据
            var dat = query.filter(filtrer).data;
            // grid_1(query.filter().data);
        },
        pageSize: 200,
        requestStart: function (e) {
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('disable')
                }
            })
            // $('body').find('th a[class="k-grid-filter"]').css({display: 'none'});
        },
        requestEnd: function (e) {
            let response = e.response;
            if (response && response['message']) {
                $.messager.show({title: '提示', msg: response['message']})
            }
            $('.easyui-linkbutton').each(function (index, item) {
                let btn = $(item);
                if (btn.linkbutton('options').text === '查询' || (btn.linkbutton('options').text === '过滤')) {
                    btn.linkbutton('enable')
                }
            })
            // $('body').find('th a[class="k-grid-filter"]').css({display: 'none'});
        }
    });
    let columns = [
        {
            field: "no",
            title: "#",
            filterable: false,
            template: "<span class='row_number'></span>",
            width: 40
        },
        // {
        //     field: "is_show_order",
        //     title: '排单显示',
        //     width: 93,
        //     attributes: {'class': 'kendo-custum-char'},
        //     headerAttributes: {style: 'text-align:center;'},
        //     footerAttributes: {style: 'color: red;text-align:center;'},
        //     filterable: {multi: true, search: true, dataSource: is_show_order}
        // },
        // {
        //     field: "company_name",
        //     title: '客户',
        //     width: 93,
        //     footerTemplate: '总计:',
        //     attributes: {'class': 'kendo-custum-char'},
        //     headerAttributes: {style: 'text-align:center;'},
        //     footerAttributes: {style: 'color: red;text-align:center;'},
        //     filterable: {multi: true, search: true, dataSource: company_name}
        // },
        // {
        //     field: "alias",
        //     title: '客户单号',
        //     width: 88,
        //     filterable: false,
        //     headerAttributes: {style: 'text-align:center;'},
        //     attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'}
        // },
        {
            field: "bill_code",
            title: '订单号',
            width: 93,
            footerTemplate: '总计:',
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {style: 'text-align:center;'},
            footerAttributes: {style: 'color: red;text-align:center;'},
            filterable: {multi: true, search: true}
        },
        {
            field: "billDate",
            title: '单据日期',
            width: 85,
            format: "{0: yyyy-MM-dd}",
            filterable: false,
            headerAttributes: {style: 'text-align:center;'},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'}
        },
        {
            field: "shippingDate",
            title: '出货日期',
            width: 85,
            format: "{0: yyyy-MM-dd}",
            filterable: false,
            headerAttributes: {style: 'text-align:center;'},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'}
        },
        {
            field: "product_name",
            title: '品名',
            width: 88,
            // filterable: false,
            filterable: {multi: true, search: true, dataSource: product_name},
            headerAttributes: {style: 'text-align:center;'},
            attributes: {style: 'white-space:nowrap;text-overflow:ellipsis;'}
        },
        {
            field: 'product_specification',
            title: '定长定重',
            width: 95,
            filterable: false,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'fabric_specification',
            title: '克重',  /*原坯布规格*/
            width: 95,
            filterable: false,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'color',
            title: '颜色',
            width: 95,
            filterable: false,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'kilo',
            title: '计划公斤',
            width: 80,
            template: item => {
                return item.kilo ? parseFloat(item.kilo).toFixed(1) : '';
            },
            footerTemplate: '#=kendo.format("{0:n1}",sum)#',
            footerAttributes: {style: 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            filterable: false,
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'low_weights',
            title: '车号',
            width: 90,
            filterable: false,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'rkps',
            title: '入库匹数',
            width: 90,
            template: item => {
                return item.rkps ? parseFloat(item.rkps).toFixed(0) : '';
            },
            footerTemplate: '#=kendo.format("{0:n1}",sum)#',
            footerAttributes: {style: 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            filterable: false,
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'rkqty',
            title: '入库公斤',
            width: 90,
            template: item => {
                return item.rkqty ? parseFloat(item.rkqty).toFixed(1) : '';
            },
            footerTemplate: '#=kendo.format("{0:n1}",sum)#',
            footerAttributes: {style: 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            filterable: false,
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'yfhps',
            title: '预发货匹数',
            width: 90,
            template: item => {
                return item.yfhps ? parseFloat(item.yfhps).toFixed(0) : '';
            },
            footerTemplate: '#=kendo.format("{0:n1}",sum)#',
            footerAttributes: {style: 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            filterable: false,
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'yfhqty',
            title: '预发货公斤',
            width: 90,
            template: item => {
                return item.yfhqty ? parseFloat(item.yfhqty).toFixed(1) : '';
            },
            footerTemplate: '#=kendo.format("{0:n1}",sum)#',
            footerAttributes: {style: 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            filterable: false,
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'fhps',
            title: '发货匹数',
            width: 90,
            template: item => {
                return item.fhps ? parseFloat(item.fhps).toFixed(0) : '';
            },
            footerTemplate: '#=kendo.format("{0:n1}",sum)#',
            footerAttributes: {style: 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            filterable: false,
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'fhqty',
            title: '发货公斤',
            width: 90,
            template: item => {
                return item.fhqty ? parseFloat(item.fhqty).toFixed(1) : '';
            },
            footerTemplate: '#=kendo.format("{0:n1}",sum)#',
            footerAttributes: {style: 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            filterable: false,
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'kcps',
            title: '库存匹数',
            width: 90,
            template: item => {
                return item.kcps ? parseFloat(item.kcps).toFixed(0) : '';
            },
            footerTemplate: '#=kendo.format("{0:n1}",sum)#',
            footerAttributes: {style: 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            filterable: false,
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'kcqty',
            title: '库存公斤',
            width: 90,
            template: item => {
                return item.kcqty ? parseFloat(item.kcqty).toFixed(1) : '';
            },
            footerTemplate: '#=kendo.format("{0:n1}",sum)#',
            footerAttributes: {style: 'text-align:right;'},
            attributes: {'class': 'kendo-custum-number'},
            filterable: false,
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'machine_qty',
            title: '上机数',
            width: 90,
            filterable: false,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'yarn_total',
            title: '总经',
            width: 90,
            filterable: false,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'longitude',
            title: '经纱',
            width: 90,
            filterable: false,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'latitude',
            title: '纬纱',
            width: 90,
            filterable: false,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'yarn_long',
            title: '经长',
            width: 90,
            filterable: false,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'latilong',
            title: '经纬密度',
            width: 90,
            filterable: false,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'fabric_width',
            title: '坯布门幅',
            width: 90,
            filterable: false,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'kou_width',
            title: '筘幅',
            width: 90,
            filterable: false,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'remark',
            title: '备注',
            width: 90,
            filterable: {multi: true, search: true},
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'create_user',
            title: '制单人',
            width: 90,
            filterable: false,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {style: 'text-align:center;'}
        },
        {
            field: 'last_user',
            title: '修改人',
            width: 90,
            filterable: false,
            attributes: {'class': 'kendo-custum-char'},
            headerAttributes: {style: 'text-align:center;'}
        },
    ];
    let grid = $("#v_grid").kendoGrid({
        sortable: true,
        resizable: true,
        selectable: "multiple row",
        editable: false,
        filterable: {
            extra: false
        },
        dataSource: dataSource,
        columnMenu: false,
        excel: {
            fileName: "车间计划序时表.xlsx",
            proxyURL: "",
            allPages: true,
            filterable: true
        },
        height: '99%',
        pageable: {
            pageSize: 200
        },
        reorderable: true,
        dataBound: function () {
            let rows = this.items();
            let kGrid = $('#v_grid').data('kendoGrid');
            $(rows).each(function () {
                let index = $(this).index() + 1;
                let rowLabel = $(this).find(".row_number");
                $(rowLabel).html(index);
                let dataItem = kGrid.dataItem($(this));
                // let type = dataItem['mark_finished'];
                // if (type) {
                //     $(this).removeClass('k-alt');
                //     $(this).addClass('kendo-background-color-yellow');
                // }
                if (dataItem['state'] == 4) {
                    $(this).addClass('kendo-custum-non-checked');
                }
                if (Number(dataItem['machine_seq']) === 1) {
                    $(this).css('color', 'red');
                }
            });
        },
        columnHide: function (e) {
            //列隐藏事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, true, null);
        },
        columnShow: function (e) {
            //列显示事件
            let field = e.column.field;
            columnResizeEvent($('body').data('menu_id'), field, null, false, null);
        },
        columnResize: function (e) {
            //  列伸缩事件
            let field = e.column.field;
            let newWidth = e.newWidth;
            if (newWidth < 20) {
                columnResizeEvent($('body').data('menu_id'), field, null, true, null);
            } else {
                columnResizeEvent($('body').data('menu_id'), field, newWidth, null, null);
            }
        },
        columnReorder: function (e) {
            //  列拖动事件
            let newColumns = JSON.parse(JSON.stringify(e.sender.columns))
            newColumns = reorder(newColumns, e.oldIndex, e.newIndex);
            let menuId = $('body').data('menu_id');
            let col = []
            for (let i = 0; i < newColumns.length; i++) {
                if (newColumns[i]['field'])
                    col.push({
                        serialNum: i,
                        sysMenuId: menuId,
                        field: newColumns[i]['field']
                    });
            }
            $.ajax({
                url: 'sysUserTableConfig/modify/reorder',
                contentType: 'application/json',
                data: JSON.stringify(col),
                type: 'post',
                dataType: 'json',
                success: function (data) {
                }
            })
        },
    });
    let grid01 = $('#v_grid').data('kendoGrid');
    loadOptions(grid01, columns, SUFFIX, $('body').data('menu_id'));
    grid01.setOptions({
        columns: columns
    });

    //region 初始化下拉框
    initCombobox(grid01.getOptions());
    //endregion

    grid.on('click', 'tr', function (e) {
        let kGrid = $("#v_grid").data("kendoGrid");
        let dataItem = kGrid.dataItem(e.currentTarget);
        if (dataItem == undefined) {
            $.messager.alert('提示', '未选中!', 'warning');
            return;
        }
        let mark_finished = dataItem['state'];
        if (mark_finished == 4) {
            $('#btn_finish').linkbutton('disable');
            $('#btn_cancel_finish').linkbutton('enable');
        } else {
            $('#btn_finish').linkbutton('enable');
            $('#btn_cancel_finish').linkbutton('disable');
        }
        // if (dataItem['is_audit']) {
        //     $('#btn_cancel_audit').linkbutton('enable')
        // } else {
        //     $('#btn_cancel_audit').linkbutton('disable')
        // }
    })
    grid.on('dblclick', 'tr', function (e) {
        //  双击打开原单
        let kGrid = $("#v_grid").data("kendoGrid");
        let dataItem = kGrid.dataItem(e.currentTarget);
        if (dataItem == undefined) {
            $.messager.alert('提示', '未选中!', 'warning');
            return;
        }
        planColumns[2].editor.options.readonly = true;
        $.ajax({
            url: `producePlan/queryDtoByPk/${dataItem.id}`,
            type: 'GET',
            dataType: 'json'
        }).then(data => {
            if (data != undefined && data.state == 1) {
                $.formDialog.open({
                    resizable: false,
                    mode: '编辑',
                    loadData: data,
                    columns: planColumns,
                    buttons: [
                    // {
                    //     text: '复制',
                    //     columns: planColumns,
                    //     iconCls: 'icon-page_copy',
                    //     handler: e => {
                    //         let dialog = $('.form-dialog-edit');
                    //         let formData = $(dialog.find('form')).serializeObject();
                    //         // formData.greyfabricDate = getDay(7);
                    //         // formData.submitDate = getDay(14);
                    //         // formData.planDate = getDay(0);
                    //         // var time = new Date();
                    //         // formData.planDate = time.toLocaleDateString();
                    //         // formData.submitDate = time.toLocaleDateString();
                    //         formData.planDate = GetDateStr(0);
                    //         formData.greyfabricDate = GetDateStr(7);
                    //         formData.submitDate = GetDateStr(14);
                    //         $.get('planTemplate/getNewPlanCode', {}, data => {
                    //             formData.id = 0;
                    //             formData.planCode = data.data;
                    //             loadPlanFormByData($('.form-dialog-edit form'),formData);
                    //         }, 'json');
                    //     }
                    // },
                    // {
                    //     text: '打印',
                    //     iconCls: 'icon-print', handler: e => {
                    //         btn_print();
                    //     }
                    // },
                    {
                        text: '刷新缓存', iconCls: 'icon-reload', handler: e => {
                            $('input').each(function (item, index) {
                                try {
                                    if ($(this).hasClass('easyui-combobox')) {
                                        $(this).combobox('reload');
                                    } else if ($(this).hasClass('easyui-combogrid')) {
                                        $(this).combogrid('grid').datagrid('reload');
                                    } else if ($(this).hasClass('easyui-combotree')) {
                                        $(this).combotree('tree').tree('reload');
                                    }
                                } catch (e) {
                                    console.table(e);
                                }
                            });
                        }
                    },
                    {
                        text: '保存',
                        iconCls: 'icon-save',
                        handler: e => {
                            let dialog = $('.form-dialog-edit');
                            if (!$(dialog.find('form')).form('validate')) {
                                return;
                            }
                            let formData = $(dialog.find('form')).serializeObject();
                            formData.orderCodeYear = null;
                            let url = "";
                            if( formData.id === '0' )
                                url = 'producePlan/insertSelective'
                            else
                                url = 'producePlan/updateSelective';
                            //  修改
                            $.messager.progress({
                                title: '',
                                msg: '请稍等...',
                                interval: 5000
                            });
                            $.ajax({
                                url: url,
                                type: 'POST',
                                dataType: 'json',
                                data: JSON.stringify(formData),
                                contentType: 'application/json',
                                success: function (data) {
                                    if (data.success) {
                                        btn_search();
                                        dialog.dialog('close');
                                        planColumns[2].editor.options.readonly = false;
                                        $.messager.show({title: '提示', msg: data.message});
                                    } else {
                                        $.messager.alert('提示', data.message, 'warning');
                                    }
                                },
                                complete: function () {
                                    planColumns[2].editor.options.readonly = false;
                                    $.messager.progress('close');
                                }
                            })
                        }
                    },
                    {
                        text: '取消',
                        iconCls: 'icon-cancel', handler: e => {
                            planColumns[2].editor.options.readonly = false;
                            $('.form-dialog-edit').dialog('close');
                        }
                    }],
                    width: 639,
                    height: 'auto',
                })
            }
        }, () => {
        });
    });
    /*grid.on('contextmenu', 'tr', function (e) {
        e.preventDefault();
        let kGrid = $('#v_grid').data('kendoGrid');
        kGrid.clearSelection();
        kGrid.select(e.currentTarget);
        let dataItem = kGrid.dataItem(e.currentTarget);
        let clickTitle = dataItem['is_show_order'] == '是' ? '取消显示' : '排单显示';
        let div = $(`<div class="easyui-menu">
<!--                         <div data-options="name:'查看明细',iconCls:'icon-pictures'">查看明细</div>-->
                         <div data-options="name:'${clickTitle}',iconCls:'icon-eye'">${clickTitle}</div>
                     </div>`);
        $('body').append(div);
        div.menu({
            onClick: function (item) {
                let name = item.text;
                let planPk = dataItem['id'];
                switch (name) {
                    case '查看明细':
                        let dialog = $(`
                            <div>
                                <div class="easyui-dialog" data-options="width:800,height:800,modal:true,title:'查看明细',
                                                                         onClose:function(){$(this).dialog('destroy')},   
                                                                         iconCls:'icon-edit'">
                                    <div class="easyui-layout" data-options="fit:true">
                                        <div data-options="region:'north',height:'auto'" style="padding: 5px;">
<!--                                            <a class="easyui-linkbutton btn-modify" id="btn_add_modify" data-options="iconCls:'icon-add',disabled:true,onClick:btn_add_modify">增加调整</a>-->
<!--                                            <a class="easyui-linkbutton btn-remove-modify" id="btn_remove_modify" data-options="iconCls:'icon-cancel',disabled:true,onClick:btn_remove_modify">删除调整</a>-->
                                            <a class="easyui-linkbutton btn-order-finished" id="btn_finished" data-options="iconCls:'icon-ok',onClick:btn_finish">订单完成</a>
<!--                                            <a class="easyui-linkbutton btn_print" data-options="iconCls:'icon-print',onClick:btn_print">打印</a>-->
                                            <a class="easyui-linkbutton btn-cancel" data-options="iconCls:'icon-no',onClick:btn_cancel">作废</a>
                                        </div>
                                        <div data-options="region:'center'">
                                            <div class="easyui-layout" data-options="fit:true">
                                                <div data-options="region:'north',height:'auto'">
                                                   <form id="input_form" style="width: 100%;height: 100%;">
                                                    <div class="form-row">
                                                        <input name="contactCompanyName" class="easyui-textbox" data-options="cls: 'input-blue',readonly:true,width:670,label:'客户：'">
                                                    </div>
                                                   <div class="form-row">
                                                        <input name="productName" class="easyui-textbox" data-options="cls: 'input-blue',readonly:true,width:670,label:'品名规格：'">
                                                     </div>
                                                    <div class="form-row">
                                                        <input name="planKilo" class="easyui-numberbox" data-options="cls: 'input-blue',width:163,readonly:true,label:'计划公斤：',precision:1">
                                                        <input name="sendKilo" class="easyui-numberbox" data-options="cls: 'input-blue',width:163,readonly:true,label:'已发公斤：',precision:1">
                                                        <input name="planRemainKilo" class="easyui-numberbox" data-options="cls: 'input-blue',width:163,readonly:true,label:'剩余公斤：',precision:1">
                                                    </div>
                                                     <div class="form-row">
                                                        <input name="inputPairs" class="easyui-numberbox" data-options="cls: 'input-blue',width:163,readonly:true,label:'总入库匹：',precision:0">
                                                        <input name="inputKilo" class="easyui-numberbox" data-options="cls: 'input-blue',width:163,readonly:true,label:'总入库重：',precision:1">
                                                        <input name="greyfabricPrice" class="easyui-numberbox" data-options="cls: 'input-blue',width:163,readonly:true,label:'默认单价：',precision:2">
                                                    </div>
                                                    <div class="form-row">
                                                        <input name="remainPairs" class="easyui-numberbox" data-options="cls: 'input-blue',width:163,label:'库存匹数：',precision:0">
                                                        <input name="remainKilo" class="easyui-numberbox" data-options="cls: 'input-blue',width:163,label:'库存公斤：',precision:1">
                                                    </div>
                                                     <div class="form-row">
                                                        <a style="margin-left: 70px;" class="easyui-linkbutton pull-right" data-options="iconCls:'icon-reload',onClick:btn_update_storage">库存更新</a>
                                                     </div>
                                                   </form>
                                                </div>
                                                <div data-options="region:'center'">
                                                    <div class="easyui-tabs" data-options="fit:true,onSelect:function(title,index){
                                                                 switch(index){
                                                                    case 0:
                                                                         $('#btn_add_modify').linkbutton('disable');
                                                                         $('#btn_remove_modify').linkbutton('disable');
                                                                        break;
                                                                    case 1:
                                                                         $('#btn_add_modify').linkbutton('disable');
                                                                         $('#btn_remove_modify').linkbutton('disable');
                                                                        break;
                                                                    case 2:
                                                                         $('#btn_add_modify').linkbutton('enable');
                                                                         $('#btn_remove_modify').linkbutton('enable');
                                                                        break;        
                                                                 }   
                                                        }">
                                                        <div data-options="title:'入库明细'">
                                                            <table id="input_dtl"></table>
                                                        </div>
                                                        <div data-options="title:'发货明细'">
                                                            <table id="send_dtl"></table>
                                                        </div>
                                                        <div data-options="title:'库存调整'">
                                                            <table id="storage_dtl"></table>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        `);
                        $.parser.onComplete = function (context) {
                            //  入库明细
                            let column1 = [[
                                {field: 'id', hidden: true, title: '编号'},
                                {field: 'createdate', title: '入库时间', width: 120, halign: 'center', align: 'center'},
                                {
                                    field: 'computer_name',
                                    title: '打卷机号',
                                    width: 160,
                                    halign: 'center',
                                    align: 'center'
                                },
                                {
                                    field: 'machine_type',
                                    title: '机台号',
                                    width: 135,
                                    halign: 'center',
                                    align: 'center'
                                },
                                {
                                    field: 'input_pairs',
                                    title: '匹数',
                                    width: 80,
                                    halign: 'center',
                                    align: 'right',
                                    formatter: (v, r, i) => v ? parseFloat(v).toFixed(0) : ''
                                },
                                {
                                    field: 'input_kilo',
                                    title: '公斤数',
                                    width: 80,
                                    halign: 'center',
                                    align: 'right',
                                    formatter: (v, r, i) => v ? parseFloat(v).toFixed(1) : ''
                                },
                                {field: 'remarks', title: '备注', width: 120, halign: 'center', align: 'center'},
                            ]];

                            function rk(columns) {
                                $('#input_dtl').datagrid({
                                    striped: true,
                                    fit: true,
                                    sortable: true,
                                    columns: columns,
                                    rownumbers: true,
                                    remoteSort: false,
                                    showFooter: true,
                                    singleSelect: true,
                                    onLoadSuccess: function () {
                                        let rows = $(this).datagrid('getRows') || [];
                                        $(this).datagrid('reloadFooter', [{
                                            createdate: '合计',
                                            input_pairs: calculateSum(rows, 'input_pairs', 0),
                                            input_kilo: calculateSum(rows, 'input_kilo', 1),
                                        }])
                                    },
                                    onResizeColumn: function (f, w) {
                                        columnResizeEvent($('body').data('menu_id'), f, w, null, null, '_rk');
                                    },
                                })

                            }

                            //  发货明细
                            let column2 = [[
                                {field: 'send_date', title: '发货时间', width: 120, halign: 'center', align: 'center'},
                                {field: 'billcode', title: '发货单号', width: 120, halign: 'center', align: 'center'},
                                {field: 'client_name', title: '客户', width: 120, halign: 'center', align: 'center'},
                                {field: 'address', title: '收货单位', width: 120, halign: 'center', align: 'center'},
                                {
                                    field: 'send_pairs',
                                    title: '匹数',
                                    width: 80,
                                    halign: 'center',
                                    align: 'right',
                                    formatter: (v, r, i) => v ? parseFloat(v).toFixed(0) : ''
                                },
                                {
                                    field: 'send_kilo',
                                    title: '重量',
                                    width: 80,
                                    halign: 'center',
                                    align: 'right',
                                    formatter: (v, r, i) => v ? parseFloat(v).toFixed(1) : ''
                                },
                                {field: 'remarks', title: '备注', width: 120, halign: 'center', align: 'center'},
                            ]];

                            function fh(columns) {
                                $('#send_dtl').datagrid({
                                    data: [],
                                    striped: true,
                                    fit: true,
                                    sortable: true,
                                    rownumbers: true,
                                    remoteSort: false,
                                    showFooter: true,
                                    singleSelect: true,
                                    columns: columns,
                                    onLoadSuccess: function () {
                                        let rows = $(this).datagrid('getRows') || [];
                                        $(this).datagrid('reloadFooter', [{
                                            send_date: '合计',
                                            send_pairs: calculateSum(rows, 'send_pairs', 0),
                                            send_kilo: calculateSum(rows, 'send_kilo', 1),
                                        }])
                                    },
                                    onResizeColumn: function (f, w) {
                                        columnResizeEvent($('body').data('menu_id'), f, w, null, null, '_fh');
                                    },
                                })
                            }

                            //  库存调整
                            let column3 = [[
                                {field: 'id', hidden: true, title: '编号'},
                                {field: 'jrkbill_date', width: 135, halign: 'center', align: 'center', title: '日期'},
                                {field: 'bill_type', width: 100, halign: 'center', align: 'center', title: '类型'},
                                {
                                    field: 'pairs',
                                    width: 80,
                                    halign: 'center',
                                    align: 'right',
                                    title: '匹数',
                                    formatter: (v, r, i) => v ? parseFloat(v).toFixed(0) : ''
                                },
                                {
                                    field: 'kilo',
                                    width: 115,
                                    halign: 'center',
                                    align: 'right',
                                    title: '公斤',
                                    formatter: (v, r, i) => v ? parseFloat(v).toFixed(1) : ''
                                },
                                {
                                    field: 'remain_pairs',
                                    width: 90,
                                    halign: 'center',
                                    align: 'right',
                                    title: '库存匹数',
                                    formatter: (v, r, i) => v ? parseFloat(v).toFixed(0) : ''
                                },
                                {
                                    field: 'remain_kilo',
                                    width: 115,
                                    halign: 'center',
                                    align: 'right',
                                    title: '库存公斤',
                                    formatter: (v, r, i) => v ? parseFloat(v).toFixed(1) : ''
                                },
                                {field: 'remarks', width: 200, halign: 'center', align: 'center', title: '备注'},
                                {
                                    field: 'address',
                                    width: 200,
                                    hidden: true,
                                    halign: 'center',
                                    align: 'center',
                                    title: '收货地址'
                                },
                            ]];

                            function kc(columns) {
                                $('#storage_dtl').datagrid({
                                    data: [],
                                    striped: true,
                                    fit: true,
                                    sortable: true,
                                    rownumbers: true,
                                    remoteSort: false,
                                    showFooter: true,
                                    singleSelect: true,
                                    columns: columns,
                                    onDblClickRow: function (index, row) {
                                        if (row != undefined && row['id']) {
                                            let loadData = {
                                                id: row.id,
                                                jrkbillDate: kendo.toString(kendo.parseDate(row['order_date']), 'yyyy-MM-dd HH:mm:ss') || '',
                                                planId: row['plan_id'],
                                                billType: row['bill_type'],
                                                pairs: row['pairs'],
                                                qty: row['kilo'],
                                                price: row['price'] || 0,
                                                address: row['address'],
                                                clientName: row['client_name'],
                                                remarks: row['remarks'],
                                            }
                                            btn_add_modify(loadData);
                                        }
                                    },
                                    onLoadSuccess: function () {
                                        let rows = $(this).datagrid('getRows') || [];
                                        $(this).datagrid('reloadFooter', [{
                                            plan_date: '合计',
                                            pairs: calculateSum(rows, 'pairs', 0),
                                            kilo: calculateSum(rows, 'kilo', 1),
                                        }])
                                    },
                                    onResizeColumn: function (f, w) {
                                        columnResizeEvent($('body').data('menu_id'), f, w, null, null, '_kc');
                                    },
                                });
                            }

                            setDatagridColumnOpts($('body').data('menu_id'), $('#input_dtl'), column1, rk, '_rk');
                            setDatagridColumnOpts($('body').data('menu_id'), $('#send_dtl'), column2, fh, '_fh');
                            setDatagridColumnOpts($('body').data('menu_id'), $('#storage_dtl'), column3, kc, '_kc');
                            $.get('plan/report/detail/' + dataItem.id, {}, data => {
                                if (data) {
                                    $('#input_form').form('load', data);
                                    $('#input_dtl').datagrid('loadData', data['inputDtl'] || []);// 入库明细
                                    $('#send_dtl').datagrid('loadData', data['sendDtl'] || []); // 发货明细
                                    $('#storage_dtl').datagrid('loadData', data['storageDtl'] || []); // 库存调整
                                }
                            }, 'json');
                            $.parser.onComplete = function () {
                            }
                        };
                        $.parser.parse(dialog);
                        break;
                        break;
                    case '排单显示':
                        $.ajax({
                            url: 'plan/modify/showstate',
                            type: 'POST',
                            data: {state: true, id: planPk},
                            dataType: 'json',
                            traditional: true,
                            success: function (data) {
                                if (data.success) {
                                    btn_search();
                                } else {
                                    messagerAlert(data.message);
                                }
                            }
                        })
                        break;
                    case '取消显示':
                        $.ajax({
                            url: 'plan/modify/showstate',
                            data: {state: false, id: planPk},
                            type: 'POST',
                            dataType: 'json',
                            traditional: true,
                            success: function (data) {
                                if (data.success) {
                                    btn_search();
                                } else {
                                    messagerAlert(data.message);
                                }
                            }
                        })
                        break;
                }
            },
        });
        div.menu('show', {
            left: e.pageX,
            top: e.pageY
        })
    });*/
}

//  新增计划（新增单据）
function btn_add() {
    // $.ajax({
    //     url: 'producePlan/maxOrderCode',
    //     contentType: 'application/json',
    //     type: 'POST',
    //     dataType: 'json',
    //     success: function (data) {
    //         planColumns[2].editor.options.value = data.data;
            //  新增计划
            $.formDialog.open({
                mode: '编辑',
                resizable: false,
                columns: planColumns,
                width: 692,
                height: 'auto',
                buttons: [
                    // {
                    // text: '保存当前模板',
                    // iconCls: 'icon-plugin_link',
                    // handler: e => {
                    //     let dialog = $('.form-dialog-edit');
                    //     let param = $(dialog.find('form')).serializeObject();
                    //     $.messager.progress({
                    //         title: '',
                    //         msg: '请稍等...',
                    //         interval: 5000
                    //     });
                    //     $.ajax({
                    //         url: 'planTemplate/updateSelective/default',
                    //         type: 'POST',
                    //         dataType: 'json',
                    //         data: param,
                    //         success: function (data) {
                    //             if (data.success) {
                    //                 $.messager.show({title: '提示', msg: data.message});
                    //             } else {
                    //                 $.messager.alert('提示', data.message, 'warning');
                    //             }
                    //         },
                    //         complete: function () {
                    //             $.messager.progress('close');
                    //         }
                    //     })
                    // }
                    // },
                    {
                        text: '刷新缓存', iconCls: 'icon-reload', handler: e => {
                            $('input').each(function (item, index) {
                                try {
                                    if ($(this).hasClass('easyui-combobox')) {
                                        $(this).combobox('reload');
                                    } else if ($(this).hasClass('easyui-combogrid')) {
                                        $(this).combogrid('grid').datagrid('reload');
                                    } else if ($(this).hasClass('easyui-combotree')) {
                                        $(this).combotree('tree').tree('reload');
                                    }
                                } catch (e) {
                                    console.table(e);
                                }
                            });
                        }
                    }, {
                        text: '保存并新增',
                        iconCls: 'icon-add',
                        handler: e => {
                            let dialog = $('.form-dialog-edit');
                            if (!$(dialog.find('form')).form('validate')) {
                                return;
                            }
                            let formData = $(dialog.find('form')).serializeObject();
                            formData.billCode = formData.code;
                            // formData.orderCodeYear = null;
                            let url = '';
                            if (formData.id) {
                                url = 'producePlan/updateSelective';
                            } else {
                                url = 'producePlan/insertSelective';
                            }
                            //  保存
                            $.messager.progress({
                                title: '',
                                msg: '请稍等...',
                                interval: 5000
                            });
                            $.ajax({
                                url: url,
                                type: 'POST',
                                dataType: 'json',
                                data: JSON.stringify(formData),
                                contentType: 'application/json',
                                success: function (data) {
                                    if (data.success) {
                                        btn_search();
                                        loadPlanForm($('.form-dialog-edit form'));
                                        $.messager.show({title: '提示', msg: data.message});
                                        // btn_plan();
                                    } else {
                                        $.messager.alert('提示', data.message, 'warning');
                                    }
                                },
                                complete: function () {
                                    $.messager.progress('close');
                                }
                            })
                        }
                    },
                    {
                        text: '复制',
                        iconCls: 'icon-page_copy',
                        handler: e => {
                            let dialog = $('.form-dialog-edit');
                            $(dialog.find('form')).form('load', {
                                id: null,
                                planCode: ''
                            });
                            $.formDialog.enableEditing();
                            $.formDialog.enableBtn(['保存并新增', '保存', '退出']);
                        }
                    }, {
                        text: '修改',
                        iconCls: 'icon-edit',
                        handler: e => {
                            $.formDialog.enableEditing();
                            $.formDialog.enableBtn(['保存并新增', '保存', '退出']);
                        }
                    }, {
                        text: '保存',
                        iconCls: 'icon-save',
                        handler: e => {
                            let form = $.formDialog.getForm();
                            let dialog = $('.form-dialog-edit');
                            if (!$(form).form('validate')) {
                                return;
                            }
                            let ProducePlan = $(form).serializeObject();
                            ProducePlan.billCode = ProducePlan.code;
                            // ProducePlan.orderCodeYear = null;
                            let url = '';
                            if (ProducePlan.id) {
                                url = 'producePlan/updateSelective';
                            } else {
                                url = 'producePlan/insertSelective';
                            }
                            //  保存
                            $.messager.progress({
                                title: '',
                                msg: '请稍等...',
                                interval: 5000
                            });
                            $.ajax({
                                url: url,
                                type: 'POST',
                                dataType: 'json',
                                data: JSON.stringify(ProducePlan),
                                contentType: 'application/json',
                                success: function (data) {
                                    if (data.success) {
                                        btn_search();
                                        $.formDialog.disableEditing();
                                        $.formDialog.enableBtn(['复制', '修改', '退出']);
                                        $(dialog.find('form')).eq(0).form('load', data.data);
                                        $.messager.show({title: '提示', msg: data.message});
                                        // btn_plan();
                                        $.messager.progress('close');
                                    } else {
                                        $.messager.alert('提示', data.message, 'warning');
                                    }
                                },
                                complete: function () {
                                    $.messager.progress('close');
                                }
                            })
                        }
                    }, {
                        text: '退出',
                        iconCls: 'icon-cancel',
                        handler: e => {
                            $.formDialog.close();
                        }
                    }],
            });
            loadPlanForm($('.form-dialog-edit form'));
            $.formDialog.disableBtn(['修改', '复制']);
    //     },
    //     error: function (e) {
    //         console.log(e);
    //     }
    // });

}

function btn_plan() {
    var grid = $("#v_grid").data("kendoGrid");
    var selectedRows = grid.select();
    var ids = [];
    let orderCodes = [];
    selectedRows.each(function() {
        ids.push(grid.dataItem(this).id);
        orderCodes.push(grid.dataItem(this).order_code_year);
    });

    $.messager.confirm('提示', '确定生成机台卡片吗？', function (r) {
        if (r) {
            //检测是否已生成卡号
            $.ajax({
                url: 'dyeFabricPlan/havePlan',
                type: 'POST',
                dataType: 'json',
                data: JSON.stringify(orderCodes),
                contentType: 'application/json',
                success: function (data) {
                    if (data.message == '200') {
                        $.ajax({
                            url: 'dyeFabricPlan/syncPlan',
                            type: 'POST',
                            dataType: 'json',
                            data: JSON.stringify(ids),
                            contentType: 'application/json',
                            success: function (data) {
                                console.log(data);
                                $.messager.alert('提示', '卡片生成成功', 'warning');
                            },
                            complete: function () {
                                $.messager.progress('close');
                            }
                        })
                    } else {
                        $.messager.confirm('提示', '检测到编号为' + data.message + '的订单已生成过卡片了，确定继续生成吗？', function (r) {
                            if (r) {
                                $.ajax({
                                    url: 'dyeFabricPlan/syncPlan',
                                    type: 'POST',
                                    dataType: 'json',
                                    data: JSON.stringify(ids),
                                    contentType: 'application/json',
                                    success: function (data) {
                                        console.log(data);
                                    },
                                    complete: function () {
                                        $.messager.progress('close');
                                    }
                                })
                            }
                        })
                    }
                },
                complete: function () {
                    $.messager.progress('close');
                }
            })
        }
    })
}

function btn_KCMX() {
    var grid = $("#v_grid").data("kendoGrid");
    var selectedRows = grid.select();
    var ids = [];
    selectedRows.each(function() {
        ids.push(grid.dataItem(this).id);
    });
    $.ajax({
        url: 'producePlan/selectByKCMX/' + ids[0],
        type: 'GET',
        success: function (data) {
            if (!data.length) {
                $.messager.show({title: '提示', msg: '未找到相关明细！！'});
            }else {
                $('#grid_detail').window('open');
                $('#grid').datagrid({
                    url: 'producePlan/selectByKCMX/' + ids[0],
                    method: 'GET',
                    fit: true,
                    rownumbers: true,
                    showFooter: true,
                    fitColumns: false,
                    striped: true,
                    remoteSort: false,
                    singleSelect: true,
                    columns: [[
                        {title: '卡片号',field: 'plan_code',align: 'center',width: 90, halign: 'center',sortable: true},
                        {title: '车号', field: 'low_weight', align: 'center', width: 60, halign: 'center', sortable: true},
                        {title: '入库匹数', field: 'rkps', align: 'right', width: 80, halign: 'center', sortable: true},
                        {title: '入库公斤', field: 'rkqty', align: 'right', width: 85, halign: 'center', sortable: true},
                        {title: '预发货匹', field: 'yfhps', align: 'center', width: 80, halign: 'center', sortable: true},
                        {title: '预发货重', field: 'yfhqty', align: 'right', width: 85, halign: 'center', sortable: true},
                        {title: '发货匹数', field: 'fhps', align: 'center', width: 80, halign: 'center', sortable: true},
                        {title: '发货公斤', field: 'fhqty', align: 'right', width: 85, halign: 'center', sortable: true},
                        {title: '库存匹数', field: 'kcps', align: 'right', width: 80, halign: 'center', sortable: true},
                        {title: '库存公斤', field: 'kcqty', align: 'right', width: 85, halign: 'center', sortable: true},

                    ]],
                    onLoadSuccess: function (data) {
                        if (data.total <= 0) {
                            $('#outbound_detail').window('close');
                            $.messager.show({title: '提示', msg: '未找到相关明细！！'});
                            let totals = {plan_code: '合计:',rkps: '',rkqty: '', yfhps: '', yfhqty: '',fhps: '', fhqty: '', kcps: '', kcqty: ''};
                            $(this).datagrid('reloadFooter', [totals]);
                        }else{

                            let totals = {plan_code: '合计:',rkps: 0,rkqty: 0, yfhps: 0, yfhqty: 0,fhps: 0, fhqty: 0, kcps: 0, kcqty: 0};
                            let rows = $(this).datagrid('getRows');
                            rows.forEach(function(row) {
                                totals.rkps += parseFloat(row.rkps) ;
                                totals.rkqty += parseFloat(row.rkqty);
                                totals.yfhps += parseFloat(row.yfhps) ;
                                totals.yfhqty += parseFloat(row.yfhqty);
                                totals.fhps += parseFloat(row.fhps) ;
                                totals.fhqty += parseFloat(row.fhqty);
                                totals.kcps += parseFloat(row.kcps);
                                totals.kcqty += parseFloat(row.kcqty);
                            });

                            totals.rkqty = parseFloat(totals.rkqty).toFixed(1);
                            totals.yfhqty = parseFloat(totals.yfhqty).toFixed(1);
                            totals.fhqty = parseFloat(totals.fhqty).toFixed(1);
                            totals.kcqty = parseFloat(totals.kcqty).toFixed(1);

                            // 更新footer
                            $(this).datagrid('reloadFooter', [totals]);
                        }
                    },
                })
            }
        }
    })
}

// 更新库存
function btn_update_storage() {
    let kGrid = $('#v_grid').data('kendoGrid');
    let dataItem = kGrid.dataItem(kGrid.select());
    let formData = $('#input_form').serializeObject() || {};
    if (!dataItem) {
        $.messager.alert('提示', '不允许更新库存库存', 'warning');
        return;
    }
    $.messager.confirm('提示', '是否确定更新库存?', function (r) {
        if (r) {
            $.post('jrkbillAdjust/insertSelective/adjust',
                {
                    planId: dataItem.id,
                    pairs: formData['remainPairs'] || 0,
                    qty: formData['remainKilo'] || 0
                },
                function (data) {
                    if (data.success) {
                        $.get(`plan/report/detail/${dataItem.id}`, {}, data => {
                            if (data) {
                                $('#input_form').form('load', data);
                                $('#input_dtl').datagrid('loadData', data['inputDtl'] || []);
                                $('#send_dtl').datagrid('loadData', data['sendDtl'] || []);
                                $('#storage_dtl').datagrid('loadData', data['storageDtl'] || []);
                            }
                        }, 'json');
                    } else {
                        $.messager.alert('提示', data.message, 'error');
                    }
                }, 'json');
        }
    })
}

function btn_add_modify(loadParam) {
    let kGrid = $('#v_grid').data('kendoGrid');
    let dataItem = kGrid.dataItem(kGrid.select());
    if (dataItem == undefined) {
        return;
    }
    let formData = $('#input_form').serializeObject() || {};
    let loadData = (loadParam && typeof loadParam == 'object') ? loadParam : {
        planId: dataItem.id,
        jrkbillDate: getCurrentDate(0, 'yyyy-MM-dd HH:mm:ss'),
        clientName: formData['contactCompanyName'],
        address: '',
        price: dataItem['greyfabric_price'] || 0
    };
    let column = [
        {
            title: '主键',
            field: 'id',
            hidden: true,
        }, {
            title: '计划单编号',
            field: 'planId',
            hidden: true,
        }, {
            title: '日期',
            field: 'jrkbillDate',
            editor: {type: 'datetimebox', options: {required: true}}
        },
        {
            title: '类型',
            field: 'billType',
            id: 'inputBillType',
            editor: {
                type: 'combobox',
                options: {
                    required: true,
                    data: [{text: '手动入库'}, {text: '盘点'}, {text: '手动出库'}],
                    textField: 'text',
                    valueField: 'text',
                    panelHeight: 'auto',
                    onLoadSuccess: function () {
                        $(this).combobox('options').limitToList = true;
                        if (!$(this).combobox('getValue')) {
                            let loadData = $(this).combobox('getData') || [];
                            let valueField = $(this).combobox('options').valueField;
                            $(this).combobox('setValue', loadData [0][valueField]);
                        }
                    },
                }
            }
        },
        {title: '匹数', field: 'pairs', editor: {type: 'numberbox', options: {precision: 0, required: true}}},
        {title: '公斤', field: 'qty', editor: {type: 'numberbox', options: {precision: 1, required: true}}},
        // {
        //     title: '客户名称',
        //     field: 'clientName',
        //     id: 'inputClientName',
        //     editor: {
        //         type: 'combobox', options: {
        //             url: 'contactCompany/listQuery', method: 'GET',
        //             textField: 'companyName', valueField: 'companyName',
        //             panelHeight: 300
        //         }
        //     }
        // },
        {
            title: '收货单位', field: 'address', id: 'inputAddress', editor: {
                type: 'combobox', options: {
                    url: 'takeDeliveryAddress/listQuery', method: 'GET',
                    textField: 'company', valueField: 'company',
                    panelHeight: 300
                }
            }
        },
        {title: '单价', field: 'price', id: 'inputPrice', editor: {type: 'numberbox', options: {precision: 2,}}},
        {title: '备注', field: 'remarks', editor: {type: 'textbox', options: {}}},
    ];
    $.formDialog.open({
        mode: loadData['id'] ? '修改调整' : '新增调整',
        columns: column,
        loadData: loadData,
        width: 330,
        height: 380,
        onOpen: function () {
            function exec(newVal) {
                if (newVal != '手动出库') {
                    $('#inputClientName').combobox('clear');
                    $('#inputAddress').combobox('clear');
                    $('#inputPrice').numberbox('clear');
                    $('#inputClientName').combobox({required: false});
                    $('#inputAddress').combobox({required: false});
                    $('#inputPrice').numberbox({required: false});
                    $('#inputClientName').combobox('readonly', true);
                    $('#inputAddress').combobox('readonly', true);
                    $('#inputPrice').numberbox('readonly', true);
                } else {
                    $('#inputClientName').combobox({required: true})
                    $('#inputAddress').combobox({required: true})
                    $('#inputPrice').numberbox({required: true})
                    $('#inputClientName').combobox('readonly', false);
                    $('#inputAddress').combobox('readonly', false);
                    $('#inputPrice').numberbox('readonly', false);
                    let formData = $('#input_form').serializeObject() || {};
                    if (!$('#inputClientName').combobox('getValue')) {
                        $('#inputClientName').combobox('setValue', formData['contactCompanyName'])
                    }
                    if (!$('#inputPrice').numberbox('getValue')) {
                        $('#inputPrice').numberbox('setValue', formData['greyfabricPrice'] || 0);
                    }
                }
            }

            let _value = $('#inputBillType').combobox('getValue');
            $('#inputBillType').combobox({
                onChange: function (newVal, oldVal) {
                    exec(newVal);
                },
                value: _value
            });
            exec(_value);
        },
        buttons: [{
            text: '保存',
            iconCls: 'icon-save',
            handler: e => {
                let dialog = $('.form-dialog-edit');
                if (!$(dialog.find('form')).form('validate')) {
                    return;
                }
                let param = $(dialog.find('form')).serializeObject();
                let url = '';
                if (param.id) {
                    url = 'jrkbillAdjust/updateSelective';
                } else {
                    url = 'jrkbillAdjust/insertSelective';
                }
                //  保存
                $.messager.progress({
                    title: '',
                    msg: '请稍等...',
                    interval: 5000
                });
                $.ajax({
                    url: url,
                    type: 'POST',
                    dataType: 'json',
                    data: param,
                    success: function (data) {
                        if (data.success) {
                            $.formDialog.disableEditing();
                            $.formDialog.enableBtn(['退出']);
                            $(dialog.find('form')).eq(0).form('load', data.data);
                            $.messager.show({title: '提示', msg: data.message});
                            $.get('plan/report/detail/' + dataItem.id, {}, function (data) {
                                if (data) {
                                    $('#input_form').form('load', data);
                                    $('#input_dtl').datagrid('loadData', data['inputDtl'] || []);
                                    $('#send_dtl').datagrid('loadData', data['sendDtl'] || []);
                                    $('#storage_dtl').datagrid('loadData', data['storageDtl'] || []);
                                }
                            }, 'json');
                        } else {
                            $.messager.alert('提示', data.message, 'warning');
                        }
                    },
                    complete: function () {
                        $.messager.progress('close');
                    }
                })
            }
        }, {
            text: '退出',
            iconCls: 'icon-cancel',
            handler: e => {
                $.formDialog.close();
            }
        }],
    });
}

/**
 * 2021年8月29日 16:21:26 chanchaw
 * 删除调整
 */
function btn_remove_modify() {
    let selected = $('#storage_dtl').datagrid('getSelected');
    if (selected == undefined) {
        $.messager.alert('提示', '未选中！', 'warning');
        return;
    }
    if (!selected['id']) {
        $.messager.alert('提示', '禁止删除非手动添加的调整！', 'warning');
        return;
    }
    let kGrid = $('#v_grid').data('kendoGrid');
    let dataItem = kGrid.dataItem(kGrid.select());
    $.messager.confirm('提示', '是否确定删除调整？', function (r) {
        if (r) {
            $.ajax({
                url: 'jrkbillAdjust/deleteByPk',
                data: {id: selected.id},
                type: 'POST',
                dataType: 'json',
            }).then(function (data) {
                if (data.success) {
                    $.messager.show({title: '提示', msg: data.message});
                    return $.ajax({
                        url: 'plan/report/detail/' + dataItem.id,
                        dataType: 'json',
                        type: 'GET'
                    })
                } else {
                    $.messager.alert('提示', data.message, 'warning');
                }
            }).then(function (data) {
                if (data) {
                    $('#input_form').form('load', data);
                    $('#input_dtl').datagrid('loadData', data['inputDtl'] || []);
                    $('#send_dtl').datagrid('loadData', data['sendDtl'] || []);
                    $('#storage_dtl').datagrid('loadData', data['storageDtl'] || []);
                }
            });
        }
    });

}

//  作废
function btn_cancel() {
    let kGrid = $('#v_grid').data('kendoGrid');
    let dataItem = kGrid.dataItem(kGrid.select());
    if (dataItem != undefined) {
        $.messager.confirm('提示', '是否确认作废', r => {
            if (r)
                $.post('plan/cancelByPk', {id: dataItem.id}, function (data) {
                    if (data.success) {
                        btn_search();
                        $.messager.show({title: '提示', msg: data.message});
                    } else {
                        $.messager.alert('提示', data.message, 'warning');
                    }
                }, 'json');
        })
    }
}

//  清楚过滤
function btn_cancel_filter() {
    $('#v_grid').data('kendoGrid').dataSource.filter({});
}

//  过滤
function btn_filter() {
    $('#v_grid').data('kendoGrid').dataSource.read({
        start: $('#start').datebox('getValue'),
        end: $('#end').datebox('getValue'),
        textField: 'Strcolumn', valueField: 'Strvalue',
    })
}

//  查询
function btn_search(stateNumber) {
    $('#v_grid').data('kendoGrid').dataSource.read({
        start: $('#start').datebox('getValue'),
        end: $('#end').datebox('getValue'),
        stateNumber: stateNumber,
    })
}

//  标记完成
function btn_finish() {
    let kGrid = $('#v_grid').data('kendoGrid');
    let dataItem = kGrid.dataItem(kGrid.select());
    if (dataItem == undefined) {
        $.messager.alert('提示', '未选中!', 'warning');
        return;
    }
    $.messager.confirm('提示', '是否完工计划单:' + dataItem.bill_code + '?', function (r) {
        if (r) {
            $.post('producePlan/finished', {id: dataItem.id}, function (data) {
                if (data.success) {
                    btn_search();
                } else {
                    $.messager.alert('提示', data.message, 'error');
                }
            }, 'json');
        }
    })
}

//  删除
function btn_delete() {
    let kGrid = $('#v_grid').data('kendoGrid');
    let dataItem = kGrid.dataItem(kGrid.select());
    if (dataItem == undefined) {
        $.messager.alert('提示', '未选中!', 'warning');
        return;
    }
    $.messager.confirm('提示', '是否删除计划?', function (r) {
        if (r) {
            $.post('plan/cancelByPk', {id: dataItem.id}, function (data) {
                if (data.success) {
                    btn_search();
                } else {
                    $.messager.alert('提示', data.message, 'error');
                }
            }, 'json');
        }
    })
}

//  作废查询
function btn_cancel_search() {
    $.createSimpleDialog.create({
        title: '白坯计划作废查询',
        width: 746,
        height: 405,
        buttons: [
            {
                text: '还原', iconCls: 'icon-add',
                handler: e => {
                    let selected = $.createSimpleDialog.getDataGrid().datagrid('getSelected');
                    if (selected == undefined) {
                        messagerAlert('请选中作废单号');
                        return;
                    }
                    messagerConfirm('是否确定恢复？', r => {
                        if (r) {
                            $.ajax({
                                url: 'plan/recoverByPk',
                                data: {id: selected.id},
                                dataType: 'json',
                                type: 'POST',
                                success: function (data) {
                                    if (data.success) {
                                        $.createSimpleDialog.destroy();
                                        btn_search();
                                    } else {
                                        messagerAlert(data.message);
                                    }
                                }
                            })
                        }
                    })
                }
            },
            {
                text: '删除', iconCls: 'icon-cancel', handler: e => {
                    let datagrid = $.createSimpleDialog.getDataGrid();
                    let selected = datagrid.datagrid('getSelected');
                    if (selected == undefined) {
                        messagerAlert('请选中作废单号');
                        return;
                    }
                    messagerConfirm('是否确定删除？删除后不可恢复？', r => {
                        if (r) {
                            $.ajax({
                                url: 'plan/deleteByPk',
                                data: {id: selected.id},
                                type: 'POST',
                                dataType: 'json',
                                success: function (data) {
                                    if (data.success) {
                                        datagrid.datagrid('reload');
                                        btn_search();
                                    } else {
                                        messagerAlert(data.message);
                                    }
                                }
                            })
                        }
                    })
                }
            },
            {
                text: '取消', iconCls: 'icon-no', handler: e => {
                    $.createSimpleDialog.destroy();
                }
            }],
        url: 'plan/report/canceled',
        columns: [[
            {title: '编号', hidden: true, width: 100, field: 'id', align: 'center', halign: 'center'},
            {title: '计划单号', width: 100, field: 'planCode', align: 'center', halign: 'center'},
            // {title: '客户', width: 100, field: 'companyName', align: 'center', halign: 'center'},
            {title: '坯布规格', width: 351, field: 'materialSpecification', align: 'center', halign: 'center'},
            {title: '计划数量', width: 70, field: 'planKilo', align: 'right', halign: 'center'},
            {title: '操作员', width: 80, field: 'cancelUserName', align: 'center', halign: 'center'},
        ]],
    })
}

function btn_cancel_finish() {
    let kGrid = $('#v_grid').data('kendoGrid');
    let dataItem = kGrid.dataItem(kGrid.select());
    if (dataItem == undefined) {
        $.messager.alert('提示', '未选中!', 'warning');
        return;
    }
    $.messager.confirm('提示', '是否取消完工?', function (r) {
        if (r) {
            $.post('producePlan/nofinished', {id: dataItem.id}, function (data) {
                if (data.success) {
                    btn_search();
                } else {
                    $.messager.alert('提示', data.message, 'error');
                }
            }, 'json');
        }
    })
}

//  打印
function btn_print() {
    let kGrid = $("#v_grid").data("kendoGrid");
    let selections = kGrid.select();
    if (selections.length <= 0) {
        $.messager.alert('提示', '请选中计划!', 'warning')
        return;
    }
    let arr = new Set();
    $(selections).each(function () {
        arr.add(kGrid.dataItem(this)['id']);
    })
    let reportlets = [];
    $.get('customize/getDatabase', {}, data => {
        if (data.success) {
            arr.forEach(item => {
                reportlets.push({
                    reportlet: data.data + '/发货结算通知单.cpt',
                    id: item,
                    database: data.data
                })
            });
            window.parent.FR.doURLPDFPrint({
                url: $(window.parent.document.body).data('report_url'),
                isPopUp: false,
                data: {
                    reportlets: reportlets
                }
            })
        }
    }, 'json');
}

//  打印
function btn_print_new() {
    $.get('customize/getDatabase', {}, data => {
        if (data.success) {
            console.log('打印请求来的数据：',data)
            let reportlets = [{
                reportlet: data.data + '/plan_storage_print.cpt',
                // start: $('#start').datebox('getValue'),
                end: $('#end').datebox('getValue'),
                // machineNum: $('#machineNum').combobox('getValue'),
                database: data.data
            }];
            console.log('构建的reportlets：', reportlets)
            window.parent.FR.doURLPDFPrint({
                url: $(window.parent.document.body).data('report_url'),
                isPopUp: false,
                data: {
                    reportlets: reportlets
                }
            })
        }
    }, 'json');
}

//  打印
function openPrint() {
        $.formDialog.open({
            mode: '打印选择',
            resizable: false,
            columns: PrintColumns,
            width: 435,
            height:100,
            // width: 'auto',
            // height: 'auto',
            // top:100,
            modal: true,
            content: 'center',
            buttons: [
            {
                text: '客户打印',
                iconCls: 'icon-print',
                width:130,
                height:90,
                handler: e => {
                    $.get('customize/getDatabase', {}, data => {
                        if (data.success) {
                            console.log('打印请求来的数据：',data)
                            let reportlets = [{
                                reportlet: data.data + '/plan_storage_print--客户汇总.cpt',
                                // start: $('#start').datebox('getValue'),
                                end: $('#end').datebox('getValue'),
                                // machineNum: $('#machineNum').combobox('getValue'),
                                database: data.data
                            }];
                            console.log('构建的reportlets：', reportlets)
                            window.parent.FR.doURLPDFPrint({
                                url: $(window.parent.document.body).data('report_url'),
                                isPopUp: false,
                                data: {
                                    reportlets: reportlets
                                }
                            })
                        }
                    }, 'json');

                }
            },
            {
                text: '头份打印',
                iconCls: 'icon-print',
                width:130,
                height:90,
                handler: e => {
                    $.get('customize/getDatabase', {}, data => {
                        if (data.success) {
                            console.log('打印请求来的数据：',data)
                            let reportlets = [{
                                reportlet: data.data + '/plan_storage_print--头份汇总.cpt',
                                // start: $('#start').datebox('getValue'),
                                end: $('#end').datebox('getValue'),
                                // machineNum: $('#machineNum').combobox('getValue'),
                                database: data.data
                            }];
                            console.log('构建的reportlets：', reportlets)
                            window.parent.FR.doURLPDFPrint({
                                url: $(window.parent.document.body).data('report_url'),
                                isPopUp: false,
                                data: {
                                    reportlets: reportlets
                                }
                            })
                        }
                    }, 'json');

                }
            },
                 {
                    text: '退出',
                    iconCls: 'icon-cancel',
                     width:130,
                     height:90,
                    handler: e => {
                        $.formDialog.close();
                    }
                }],
        });
        loadPlanForm($('.form-dialog-edit form'));
        $.formDialog.disableBtn(['修改', '复制']);
    }

/*function btn_add_sub1() {
    f(true);
}
function btn_add_sub2() {
    g(false);
}*/

function btn_open_column_list() {
    let kendoGridID = '#v_grid';
    let options = $(kendoGridID).data('kendoGrid').getOptions().columns;
    if ($('#btn_open_column_list').length <= 0) {
        let div = $(`<div data-options="resizable:true,iconCls:'icon-text_columns',width:200,height:300,modal:true,title:'列'" 
                          class="easyui-dialog" id="btn_open_column_list">
                   </div>`);
        let form = $('<form style="width: 100%;height: 100%;"></form>')
        for (let i of options) {
            if (i.field) {
                let checkbox = $(`<div style="width: 100%;height: auto;padding: 5px;">
                <input class="easyui-checkbox" name="${i.field}" data-options="label:'${i.title}',
                labelWidth:120,value:true,name:'${i.field}'">
                </div>`);
                form.append(checkbox);
            }
        }
        let container = $(`<div></div>`);
        form.appendTo(div);
        div.appendTo(container);
        $('body').append(container);
        $.parser.parse($('#btn_open_column_list').parent());
        let formData = {};
        options.map(item => {
            formData[item['field']] = item['hidden'] == undefined ? true : !item['hidden'];
        })
        $('#btn_open_column_list form').eq(0).form('load', formData);
        $('#btn_open_column_list form .easyui-checkbox').each(function () {
            //  绑定事件
            $(this).checkbox({
                onChange: function (checked) {
                    let opts = $(this).checkbox('options');
                    if (checked) {
                        $(kendoGridID).data('kendoGrid').showColumn(opts.name);
                    } else {
                        $(kendoGridID).data('kendoGrid').hideColumn(opts.name);
                    }
                }
            })
        })
    } else {
        $('#btn_open_column_list').dialog('open');
    }
}

function btn_export_excel() {
    $('#v_grid').data('kendoGrid').saveAsExcel();
}

function btn_close() {
    window.parent.closeTab();
}

//  消审
function btn_cancel_audit() {
    let kGrid = $('#v_grid').data('kendoGrid');
    let selected = kGrid.select();
    if (selected == undefined) {
        messagerAlert('请选中！');
        return;
    }
    let dataItems = [];
    selected.each(function () {
        let dataItem = kGrid.dataItem(this);
        if (dataItem.id) {
            dataItems.push(dataItem.id);
        }
    });
    if (dataItems.length <= 0) {
        messagerAlert('请选中！');
        return;
    }
    messagerConfirm('确定消审？', r => {
        if (r) {
            $.ajax({
                url: 'plan/cancelAudit',
                data: {id: dataItems},
                type: 'POST',
                dataType: 'json',
                traditional: true,
            }).then(function (data) {
                if (data.success) {
                    btn_search();
                } else {
                    messagerAlert(data.message);
                }
            })
        }
    })
}

function btn_audit() {
    messagerConfirm('确定审核所有？', r => {
        if (r) {
            $.ajax({
                url: 'plan/auditAll',
                data: {},
                type: 'POST',
                dataType: 'json',
                traditional: true,
            }).then(function (data) {
                if (data.success) {
                    btn_search();
                } else {
                    messagerAlert(data.message);
                }
            })
        }
    })
}

//  加载计划表(选择默认模板)
function loadPlanForm(form) {
    $.get('planTemplate/listQuery/default', {}, data => {
        if (Object.getOwnPropertyNames(data).length > 0) {
            delete data.id;
            $(form).form('load', data);
        }
    }, 'json');
}

// 2021年11月4日15:54:40 chanchaw
// 复制(使用现有数据填充表单)
function loadPlanFormByData(form,formData) {
    $(form).form('load', formData);
}

function stateChange(checked) {
    let stateNumber = 1;
    $('#start').datebox('disable');
    $('#end').datebox('disable');
    if (checked) {
        stateNumber = 0
        $('#start').datebox('enable');
        $('#end').datebox('enable');
    }
    btn_search(stateNumber);
}

function setState(state) {
    if (state) {
        $('#start').datebox('enable');
        $('#end').datebox('enable');
    } else {
        $('#start').datebox('disable');
        $('#end').datebox('disable');
    }
}

function ceshi() {
    // “移库”功能请求后端数据的参数
    // 显示到模态窗表格的数据源 - 排除 plan.id = 2 的计划
    const param = {'id':'2'};
    $.ajax({
        url: 'plan/reportExclude',
        contentType: 'application/json',
        data: JSON.stringify(param),
        type: 'post',
        dataType: 'json',
        success: function (data) {
            // 实际数据应该：data.data
            console.log(data);
        },
        error: function(e){
            console.log('请求移库模态窗数据源时出现异常',e);
        }
    })
}

function getDataA() {
    let kGrid = $('#v_grid').data('kendoGrid');
    let dataItem = kGrid.dataItem(kGrid.select());
    if( dataItem != undefined ) {

        var  param = {'id':'' +dataItem.id+''} ;

        }else{
        $.messager.alert('提示', '请选中一行后再进行本操作!', 'warning');
        return;
    }

    console.log('getDataA参数：id='+ dataItem.id);
    console.log(param);

    $.ajax({
        url: 'plan/reportExclude',
        contentType: 'application/json',
        data: JSON.stringify(param),
        type: 'post',
        dataType: 'json',
        success: function (cdata) {
            // 实际数据应该：data.data
            console.log("网格数据集：");
            console.log(cdata);
            getDataADatel (cdata.data,dataItem.id);
        },
        error: function(e){
            console.log('请求移库模态窗数据源时出现异常',e);
        }
    });

}

function getDataADatel(cData,oldID) {
    $.createSimpleDialog.create({
        title: '待移库白坯',
        width: 1100,
        height: 600,
        buttons: [

            {
                text: '确定移库', iconCls: 'icon-ok',
                handler: e => {
                    let selected = $.createSimpleDialog.getDataGrid().datagrid('getSelected');
                    if (selected == undefined) {
                        messagerAlert('未选择数据！');
                        return;
                    }
                    messagerConfirm('是否确定转移库存？', r => {
                        if (r) {
                            getqty(oldID,selected.id);
                        }
                    })
                }
            },
            {
                text: '取消退出', iconCls: 'icon-no', handler: e => {
                    $.createSimpleDialog.destroy();
                }
            }],
        // url: 'plan/report/canceled',
        data:cData,
        columns: [[
            {title: '编号', hidden: true, width: 70, field: 'id', align: 'center', halign: 'center'},
            {title: '计划单号', width: 80, field: 'plan_code', align: 'center', halign: 'center'},
            // {title: '客户', width: 80, field: 'company_name', align: 'center', halign: 'center'},
            {title: '品名', width: 80, field: 'product_name', align: 'center', halign: 'center'},
            {title: '头份', width: 60, field: 'greyfabric_specification', align: 'center', halign: 'center'},
            {title: '门幅', width: 70, field: 'greyfabric_width', align: 'center', halign: 'center'},
            {title: '克重', width: 70, field: 'greyfabric_weight', align: 'center', halign: 'center'},
            {title: '毛高', width: 40, field: 'meter_length', align: 'center', halign: 'center'},
            {title: '米长', width: 60, field: 'm_height', align: 'center', halign: 'center'},
            {title: '原料规格', width: 80, field: 'material_specification', align: 'center', halign: 'center'},
            {title: '批次号', width: 80, field: 'material_lot_no', align: 'center', halign: 'center'},
            {title: '库存匹', width: 50, field: 'remain_pairs', align: 'center', halign: 'center'},
            {title: '库存重', width: 80, field: 'remain_kilo', align: 'center', halign: 'center'},
            {title: '待生产重', width: 80, field: 'waitqty', align: 'center', halign: 'center'},
            {title: '剩余重', width: 80, field: 'remaining_weight', align: 'center', halign: 'center'},
            // {title: '入库时间', width: 170, field: 'createTime', align: 'right', halign: 'center',formatter: formatDateTime},
        ]],
    })
}

function add0(m){return m<10?'0'+m:m }

function formatDateTime(shijianchuo) {
//shijianchuo是整数，否则要parseInt转换
    var time = new Date(shijianchuo);
    var y = time.getFullYear();
    var m = time.getMonth()+1;
    var d = time.getDate();
    var h = time.getHours();
    var mm = time.getMinutes();
    var s = time.getSeconds();
    return y+'-'+add0(m)+'-'+add0(d)+' '+add0(h)+':'+add0(mm)+':'+add0(s);
}

// 录入公斤匹数的窗口
function getqty(oldID,NewID) {
    let param = {};
    openDialog(param, '移库数量',oldID,NewID);
    $.formDialog.enableBtn(['保存', '关闭']);
}

function openDialog(loadData, title,oldID,NewID) {
    $.formDialog.open({
        columns: materialColumns,
        loadData: loadData,
        mode: title ? title : '移库数量',
        width: 300,
        height: 220,
        buttons: [
            {
                text: '保存', iconCls: 'icon-save', handler: e => {
                    // let id=$('#id').numberbox('getValue');
                    let ps=$('#inputAmount').numberbox('getValue');
                    let qty=$('#inputKiloId').numberbox('getValue');
                    btn_moveInven(oldID,NewID,ps,qty);
                    $('.form-dialog-edit').eq(0).dialog('close');
                    $.createSimpleDialog.destroy();

                }
            },

            {
                text: '关闭', iconCls: 'icon-no', handler: e => {
                    $('.form-dialog-edit').eq(0).dialog('close');
                }
            }]
    })
}

// 移库  27
function btn_moveInven(oldID,NewID,ps,qty) {
    // 测试生成移库单据
    let param = {"ido":oldID,"idt":NewID,"pairs":Number(ps),"qty":Number(qty)};
    console.log("移库参数:");
    console.log(param);
    $.ajax({
        url: 'jrkbillAdjust/migrateStock',
        contentType: 'application/json',
        data: JSON.stringify(param),
        type: 'post',
        dataType: 'json',
        success: function (data) {
            // 后端响应来的数据：data.data
            console.log(data);
            console.log(formatDateTime(new Date()));
            window.setTimeout(function (){
                console.log(formatDateTime(new Date()));
                btn_search();  //保存之后自动刷新数据
            },1000);
        },
        error: function (e) {
            console.log('请求移库模态窗数据源时出现异常', e);
        }
    })
}

//选中事件
function initCombobox(options) {
    var columns = options.columns;
    columns.splice(0, 1);
    $('#column').combobox({
        valueField: 'field',
        textField: 'title',
        data: columns,
        editable: false
    })
}

// function getDay(day) {
//     var today = new Date(0);
//     var targetday_milliseconds = today.getTime() + 1000 * 60 * 60 * 24 * day;
//     today.setTime(targetday_milliseconds); //注意，这行是关键代码
//     var tYear = today.getFullYear();
//     var tMonth = today.getMonth();
//     var tDate = today.getDate();
//     tMonth = doHandleMonth(tMonth + 1);
//     tDate = doHandleMonth(tDate);
//     return tYear + "-" + tMonth + "-" + tDate;  // + " " + "07" + ":" + "00"
// }
//
// function doHandleMonth(month) {
//     var m = month;
//     if (month.toString().length == 1) {
//         m = "0" + month;
//     }
//     return m;
// }

function getBeforeDate(n){//n为你要传入的参数，当前为0，前一天为-1，后一天为1
    var date = new Date() ;
    var year,month,day ;
    date.setDate(date.getDate()+n);
    year = date.getFullYear();
    month = date.getMonth()+1;
    day = date.getDate() ;
    s = year + '-' + ( month < 10 ? ( '0' + month ) : month ) + '-' + ( day < 10 ? ( '0' + day ) : day) ;
    return s ;
}


function  GetDateStr(day) {
    var  dd =  new  Date();
    dd.setDate(dd.getDate()+day); //获取day天后的日期
    var  y = dd.getFullYear();
    var  m = (dd.getMonth()+1)<10? "0" +(dd.getMonth()+1):(dd.getMonth()+1); //获取当前月份的日期，不足10补0
    var  d = dd.getDate()<10? "0" +dd.getDate():dd.getDate(); //获取当前几号，不足10补0
    return  y+ "-" +m+ "-" +d;
}
// console.log( "昨天：" +GetDateStr(-1));
// console.log( "今天：" +GetDateStr(0));
// console.log( "明天：" +GetDateStr(1));